<template>
  <canvas 
    canvas-id="othelloCanvas"
    class="board"
    @touchstart="handleTouch"
    @click="handleTouch"
    :style="{ width: canvasSize + 'px', height: canvasSize + 'px' }"
  ></canvas>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useGameStore } from '@/stores/game'

const gameStore = useGameStore()
const canvasSize = ref(300)
const cellSize = computed(() => canvasSize.value / 8)
let ctx = null
let dpr = 1 // 设备像素比

// 初始化棋盘
const initBoard = (retries = 3) => {
  console.log('尝试获取 canvas 上下文，剩余重试次数:', retries)
  
  try {
    // 微信小程序获取 canvas 上下文的方式
    ctx = uni.createCanvasContext('othelloCanvas')
    
    if (ctx) {
      const systemInfo = uni.getSystemInfoSync()
      dpr = systemInfo.pixelRatio || 1
      console.log('成功获取到 canvas 上下文, dpr=', dpr)
      
      // 设置 canvas 实际宽高（通过 style 控制显示尺寸）
      drawBoard()
      drawPieces()
      
      // 提交绘制
      ctx.draw(false, () => {
        console.log('canvas 初始化绘制完成')
      })
    } else if (retries > 0) {
      setTimeout(() => initBoard(retries - 1), 100)
    } else {
      console.error('未正确获取到 canvas 上下文，重试次数已用完')
    }
  } catch (error) {
    console.error('初始化棋盘出错:', error)
    if (retries > 0) {
      setTimeout(() => initBoard(retries - 1), 100)
    }
  }
}

onMounted(() => {
  gameStore.initGame()
  // 微信小程序中可能需要延迟一点时间确保 canvas 已准备好
  setTimeout(() => {
    initBoard()
  }, 300)
})

// 绘制棋盘
const drawBoard = () => {
  if (!ctx) return
  
  ctx.setStrokeStyle('#000')
  ctx.setLineWidth(1)
  
  // 清除之前的绘制（微信小程序中 clearRect 可能不生效，所以用填充背景替代）
  ctx.setFillStyle('#009E73')
  ctx.fillRect(0, 0, canvasSize.value * dpr, canvasSize.value * dpr)
  
  // 绘制网格线（考虑像素比）
  for (let i = 0; i <= 8; i++) {
    const pos = i * cellSize.value * dpr
    
    // 竖线
    ctx.beginPath()
    ctx.moveTo(pos, 0)
    ctx.lineTo(pos, canvasSize.value * dpr)
    ctx.stroke()
    
    // 横线
    ctx.beginPath()
    ctx.moveTo(0, pos)
    ctx.lineTo(canvasSize.value * dpr, pos)
    ctx.stroke()
  }
}

// 绘制棋子
const drawPieces = () => {
  if (!ctx || !gameStore.boardState) return
  
  console.log('重新绘制棋盘和棋子')
  
  // 先绘制背景和网格
  drawBoard()
  
  // 绘制棋子（考虑像素比）
  gameStore.boardState.forEach((row, i) => {
    row.forEach((cell, j) => {
      if (cell === 'black' || cell === 'white') {
        const x = j * cellSize.value * dpr + cellSize.value * dpr / 2
        const y = i * cellSize.value * dpr + cellSize.value * dpr / 2
        const radius = cellSize.value * dpr / 2 - 2
        
        ctx.beginPath()
        ctx.arc(x, y, radius, 0, Math.PI * 2)
        ctx.setFillStyle(cell === 'black' ? '#000' : '#fff')
        ctx.fill()
        
        // 为白棋添加边框
        if (cell === 'white') {
          ctx.setStrokeStyle('#000')
          ctx.stroke()
        }
      }
    })
  })

  // 绘制合法移动提示
  ctx.setFillStyle('rgba(255, 0, 0, 0.5)')
  gameStore.validMoves.forEach((pos) => {
    const x = pos.col * cellSize.value * dpr + cellSize.value * dpr / 2
    const y = pos.row * cellSize.value * dpr + cellSize.value * dpr / 2
    
    ctx.beginPath()
    ctx.arc(x, y, 5 * dpr, 0, Math.PI * 2)
    ctx.fill()
  })
}

// 触摸事件处理
const handleTouch = (e) => {
  if (!ctx) return
  
  // 获取 canvas 节点信息
  const query = uni.createSelectorQuery()
  query.select('[canvas-id="othelloCanvas"]').boundingClientRect(data => {
    if (!data) {
      console.error('未能获取到 canvas 的位置信息')
      return
    }
    
    const touch = e.touches ? e.touches[0] : e
    let x = (touch.clientX || touch.x) - data.left
    let y = (touch.clientY || touch.y) - data.top
    
    // 考虑设备像素比
    x = x * dpr
    y = y * dpr
    
    const col = Math.floor(x / (cellSize.value * dpr))
    const row = Math.floor(y / (cellSize.value * dpr))

    // 确保坐标在有效范围内
    if (row >= 0 && row < 8 && col >= 0 && col < 8) {
      if (gameStore.placePiece(row, col)) {
        drawPieces()
        ctx.draw(false, () => {
          console.log('移动绘制完成')
        })
        console.log('成功移动:', row, col)
      } else {
        console.log('非法移动:', row, col)
      }
    }
  }).exec()
}

defineExpose({
  initBoard,
  drawPieces // 暴露以便外部调用重新绘制
})
</script>

<style scoped>
.board {
  width: 300px;
  height: 300px;
  background-color: #009E73;
}
</style>
